<template>
  <div id="cnTeam-main-container">
    <div class="left-box">
      <el-tabs v-model="tabActiveName" tab-position="left" @tab-click="tabClick">
        <el-tab-pane name="all" label="查找汉化组"/>
        <el-tab-pane name="mine" label="我的汉化组"/>
      </el-tabs>
    </div>
    <div class="right-box">
      <div class="table-top">
        <span style="width: 50px;">
        <el-button size="small" class="theme-button" type="primary" icon="el-icon-plus"
                   @click="openDrawer(null, 'save')">创建我的汉化组</el-button>
      </span>
        <span style="width: 200px;">
        <el-input
            clearable
            v-model="page.keyword"
            placeholder="请输入关键词"
            @change="flashTable"
            @keydown.enter="flashTable">
        </el-input>
      </span>
      </div>
      <div class="table-box">
        <template>
          <el-table
              v-loading="loading"
              :data="tableData"
              stripe
              max-height="calc(100vh - 180px)"
              style="width: 100%">
            <el-table-column width="80" label="logo">
              <template slot-scope="scope">
                <div class="logo-box">
                  <span class="logo-text" :style="{'background-color' : randomColor(), 'color': '#fff'}"
                        v-if="!scope.row.logoUrl">{{ scope.row.teamName[0] }}</span>
                  <img v-else loading="lazy" :src="scope.row.thumbLogoUrl ? scope.row.thumbLogoUrl : scope.row.logoUrl"
                       alt=""
                       style="width: 100%; height: 100%; object-fit: cover"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column
                show-overflow-tooltip
                prop="teamName"
                label="汉化组名">
            </el-table-column>
            <el-table-column
                show-overflow-tooltip
                prop="about"
                label="简介">
              <template slot-scope="scope">
                <span style="cursor: pointer" v-if="scope.row.about" @click="openAboutDialog(scope.row)">{{ scope.row.about }}</span>
              </template>
            </el-table-column>
            <el-table-column
                show-overflow-tooltip
                v-if="tabActiveName === 'mine'"
                prop="joinCode"
                label="邀请码"
                align="center">
              <template slot-scope="scope">
                {{ scope.row.leader ? scope.row.joinCode : '--' }}
              </template>
            </el-table-column>
            <el-table-column
                prop="memberCount"
                label="成员数"
                align="center">
            </el-table-column>
            <el-table-column
                width="100px"
                prop="heat"
                label="热门作TOP5"
                align="center">
              <template slot-scope="scope">
                <el-popover
                    :disabled="!(scope.row.hotWorks && scope.row.hotWorks.length)"
                    placement="bottom"
                    width="200"
                    trigger="click">
                  <el-carousel :autoplay="false" height="230px" indicator-position="none">
                    <el-carousel-item class="carousel-item" v-for="item in scope.row.hotWorks" :key="item.mangaId">
                      <img style="width: 100%; height: 100%; object-fit: fill; cursor: pointer" loading="lazy"
                           :src="item.thumbCoverUrl ? item.thumbCoverUrl : item.coverUrl" alt=""
                           @click="goToManga(item.mangaId)"/>
                      <h3 class="text-ellipsis" style="position: absolute; bottom: 0;left: 0;
                       display: flex; justify-content: center;
                        font-size: small; color: #FFFFFF; width: 100%; background-color: rgba(102,102,102,0.5)">
                        {{ item.name }}</h3>
                    </el-carousel-item>
                  </el-carousel>
                  <div slot="reference">
                    <el-button v-if="scope.row.hotWorks && scope.row.hotWorks.length" type="text">
                      查看
                    </el-button>
                    <span v-else>暂无</span>
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
                width="100px"
                prop="createTime"
                label="创建时间"
                align="center">
            </el-table-column>
            <el-table-column
                width="200px"
                fixed="right"
                label="操作"
                align="center">
              <template slot-scope="scope">
                <el-button v-if="scope.row.leader" @click="openDrawer(scope.row, 'edit')" type="text" size="small">编辑</el-button>
                <el-button v-if="scope.row.join" @click="$refs.memberTable.openWindow(scope.row)" type="text" size="small">查看组员</el-button>
                <el-button v-if="scope.row.leader" style="color: #F56C6C;" @click="deleted(scope.row)" type="text" size="small">删除</el-button>
                <el-button v-if="!scope.row.leader && scope.row.join" style="color: #F56C6C;" @click="quitTeam(scope.row)" type="text" size="small">退出</el-button>
                <el-button v-if="!scope.row.join" icon="el-icon-plus" class="theme-button" @click="openJoinDialog(scope.row)" type="primary" size="small">加入</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <el-pagination style="float: right; padding-top: 20px;"
                     background
                     layout="total, prev, pager, next"
                     @current-change="handleCurrentChange"
                     :total="total"
                     :page-size="page.size">
      </el-pagination>

      <cn-team-member-table ref="memberTable"/>

      <!--   新增/编辑弹窗   -->
      <el-drawer
          :title="formType === 'save' ? '创建汉化组' : '编辑汉化组'"
          size="700px"
          direction="rtl"
          :append-to-body="true"
          :show-close="false"
          :before-close="handleClose"
          :visible.sync="formVisible">
        <div id="son-drawer-main-box">
          <el-form :model="formData" :rules="formRules" ref="form" label-width="100px">
            <el-form-item style="width: 300px;" label="组名" prop="teamName">
              <el-input v-model="formData.teamName"/>
            </el-form-item>
            <el-form-item style="width: 300px;" label="邀请码" prop="joinCode">
              <el-input v-model="formData.joinCode" placeholder="未填写将自动生成" maxlength="50"></el-input>
            </el-form-item>
            <el-form-item style="width: 500px;" label="简介" prop="about">
              <el-input type="textarea"
                        v-model="formData.about"
                        :autosize="{ minRows: 2, maxRows: 5}"/>
            </el-form-item>
            <el-form-item label="logo" prop="logoUrl">
              <single-upload v-loading="uploadLoading" @getFile="getFile" @cleanup="cleanupLogo"
                             :imageUrl="formData.thumbLogoUrl ? formData.thumbLogoUrl : formData.logoUrl"
                             ref="logo"/>
            </el-form-item>
            <el-form-item>
              <el-button :loading="submitLoading" type="primary" @click="submitForm">
                {{ formType === 'save' ? '创建' : '修改' }}
              </el-button>
              <el-button @click="resetForm('form')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-drawer>

      <!--   简介弹窗   -->
      <el-dialog append-to-body width="40%" :title="aboutDialogData.teamName + '简介'" :visible.sync="aboutDialogVisible">
        <div style="white-space: pre-wrap" v-html="aboutDialogData.about"/>
      </el-dialog>

      <!--   加入汉化组弹窗   -->
      <el-dialog append-to-body width="20%" :title="'加入' + joinDialogData.teamName" :visible.sync="joinDialogVisible">
        <div id="join-box">
          <el-input class="input" v-model="joinDialogData.inputJoinCode" placeholder="请输入邀请码"/>
          <el-button class="theme-button btn" style="float: right" :loading="joinLoading" type="primary" @click="joinTeam">确认</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {cnTeamDeleted, cnTeamPage, joinTeam, quitTeam, saveCnTeam, updateCnTeam} from "@/api/cnTeamApi";
import singleUpload from "@/components/upload/upload.vue";
import {randomColor} from "@/util/colorUtil";
import {uploadFile} from "@/api/fileApi";
import CnTeamMemberTable from "@/components/cnTeam/cnTeamMemberTable.vue";

export default {
  components: {CnTeamMemberTable, singleUpload},
  data() {
    return {
      loading: false,
      tableData: [],
      tabActiveName: 'all',

      // 弹窗相关
      aboutDialogVisible: false,
      aboutDialogData: {},
      joinDialogVisible: false,
      joinDialogData: {},
      joinLoading: false,

      // 分页数据
      page: {
        page: 1,
        size: 10,
        id: null,
        keyword: ""
      },
      total: 0,
      // 表单数据
      formData: {},
      formType: 'save',
      formVisible: false,
      formRules: {
        teamName: [{required: true, message: '请输入组名', trigger: 'blur'}],
        joinCode: [{max: 50, message: '邀请码长度不能超过50个字符', trigger: 'blur'}]
      },
      logoFile: null,
      uploadLoading: false,
      submitLoading: false,
    }
  },
  methods: {
    randomColor,
    flashTable() {
      this.loading = true;
      cnTeamPage(this.page).then(res => {
        if (res.code === '200') {
          this.tableData = res.data.records;
          this.total = Number(res.data.total);
        }
      }).finally(() => {
        this.loading = false;
      })
    },
    tabClick() {
      if (this.tabActiveName === 'all') {
        this.page.isMine = false;
        this.flashTable();
      } else {
        this.page.isMine = true;
        this.flashTable();
      }
    },
    handleCurrentChange(val) {
      this.page.page = val
      this.flashTable()
    },
    openAboutDialog(row) {
      this.aboutDialogData = row;
      this.aboutDialogVisible = true;
    },
    openJoinDialog(row) {
      this.joinDialogData = row;
      this.joinDialogVisible = true;
    },
    openDrawer(row, formType) {
      this.formData = {};
      this.formType = formType;
      this.formVisible = true;
      if (formType === 'edit') {
        this.formData = row
      }
    },
    handleClose() {
      this.formVisible = false
    },
    goToManga(mangaId) {
      this.$router.push("/mgEp?id=" + mangaId)
    },
    joinTeam() {
      this.joinLoading = true;
      if (this.joinDialogData.inputJoinCode) {
        joinTeam(this.joinDialogData.tid, this.joinDialogData.inputJoinCode)
            .then(res => {
              if (res.code === '200') {
                this.$message({
                  message: '欢迎加入 ' + this.joinDialogData.teamName + ' ！',
                  type: 'success'
                })
                this.flashTable()
                this.joinDialogVisible = false;
              } else {
                this.$message({
                  message: res.msg,
                  type: 'error'
                })
              }
            }).finally(() => {
              this.joinLoading = false;
        })
      }
    },
    getFile(file) {
      this.logoFile = file;
    },
    cleanupLogo() {
      this.logoFile = null;
      this.formData.logoUrl = ''
      this.formData.thumbLogoUrl = ''
    },
    quitTeam(row) {
      this.$confirm('确定要退出该组吗？', {
        type: "warning"
      }).then(() => {
        quitTeam(row.tid).then(res => {
          if (res.code === '200') {
            this.$message({
              message: '退出成功',
              type: 'success'
            })
            this.flashTable()
          }
        })
      })
    },
    /**
     * 删除
     * @param row 行数据
     */
    deleted(row) {
      this.$confirm('此操作将永久删除该组, 是否继续?', {
        type: "warning"
      }).then(() => {
        cnTeamDeleted(row.tid).then(res => {
          if (res.code === '200') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.flashTable()
          }
        })
      })
    },
    /**
     * 提交表单
     */
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          // 当封面文件不为空时
          if (this.logoFile) {
            // 上传封面
            const formData = new FormData();
            formData.append('prefix', 'logo/' + this.formData.teamName);
            formData.append('datePrefix', false);
            formData.append('file', this.logoFile);
            this.uploadLoading = true
            let res = await uploadFile(formData)
            this.formData.logoUrl = res.data
            this.uploadLoading = false
          }
          if (this.formType === 'save') {
            // 保存漫画
            saveCnTeam(this.formData).then(res => {
              if (res.code === '200') {
                this.$message({
                  message: '创建成功，快开烤吧',
                  type: 'success'
                })
                this.flashTable()
                this.formVisible = false
                this.resetForm('form')
              } else {
                this.$message({
                  message: '创建失败',
                  type: 'error'
                })
              }
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            // 编辑漫画
            updateCnTeam(this.formData).then(res => {
              if (res.code === '200') {
                this.$message({
                  message: '编辑成功',
                  type: 'success'
                })
                this.flashTable()
                this.formVisible = false
                this.resetForm('form')
              } else {
                this.$message({
                  message: '编辑失败',
                  type: 'error'
                })
              }
            }).finally(() => {
              this.submitLoading = false
            })
          }
        }
      });
    },
    /**
     * 重置表单
     * @param formName 表单名称
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.formData = {}
      this.$refs.logo.cleanup()
      this.submitLoading = false
    }
  },
  mounted() {
    this.flashTable();
  }
}
</script>

<style scoped lang="scss">
@import url("@/scss/cnTeamTable.scss");
</style>